package com.yanqu.road.net.operator;

import com.yanqu.road.connect.Connection;
import com.yanqu.road.message.YanQuMessage;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

public class ConnectionOperator {

    private static Logger logger = LogManager.getLogger(ConnectionOperator.class.getName());


    public static int sendMsg(Connection[] connections, YanQuMessage yanQuMessage, int connectionIndex) {
        Connection connection = connections[connectionIndex % connections.length];
        yanQuMessage.setPlayerId(connectionIndex % connections.length);
        if (!isConnectionAlive(connection)) {
            int i = 0;
            for (Connection tempConn : connections) {
                if (isConnectionAlive(tempConn)) {
                    yanQuMessage.setPlayerId(i);
                    connection = tempConn;
                    break;
                }
                i++;
            }

            if (!isConnectionAlive(connection)) {
                logger.error("all conn down");
                return 0;
            }

            logger.error("connect fail : index = {} message = {}，rediscover link , index : {}" ,
                    connectionIndex % connections.length , yanQuMessage , i);
        }
        connection.write(yanQuMessage);
        return 1;
    }

    public static boolean isConnectionAlive(Connection connection) {
        return connection != null && connection.isAlive();
    }

    public static void connectionGroupWrite(Connection[] connections, YanQuMessage yanQuMessage) {
        int size = connections != null ? connections.length : 0;
        int random = (int) (Math.random() * size);
        if (yanQuMessage.getPlayerId() > 0) {
            random = (int) (yanQuMessage.getPlayerId() % connections.length);
        }
        Connection connection = connections[random];
        if (!isConnectionAlive(connection)) {
            int i = 0;
            for (Connection tempConn : connections) {
                if (isConnectionAlive(tempConn)) {
                    connection = tempConn;
                    break;
                }
                i++;
            }

            if (!isConnectionAlive(connection)) {
                logger.error("all conn down");
                return;
            }

            logger.error(" connect fail : index = {} msg = {}，rediscover link , index : {}" ,
                    random , yanQuMessage , i);
        }

        connection.write(yanQuMessage);
    }
}
